package com.pocket.mic.common.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class CommonHttpClient {

	public int commonGet(String protocol,String host,Integer port,String path,String paras)
			throws IOException {
		try {
				URL u = new URL(protocol, host, port, path
						+ paras);
				HttpURLConnection conn = (HttpURLConnection) u.openConnection();
//				conn.setRequestMethod("GET");
//				conn.setDoInput(true);
				if (conn.getResponseCode() == 200) {
//					System.out.print(IOUtils.toString(conn.getInputStream(),
//					"GBK"));
					return 200;
				} else {
					return 0;
				}
			} catch (Exception e) {
				throw new IOException("request failed", e);
			}
		}
	public int requestGet(String url){
		URL clientUrl=null;
		try {
			clientUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		if(null!=clientUrl){
			String host = clientUrl.getHost();
			String path=clientUrl.getPath();
			String query=clientUrl.getQuery();
			Integer port = clientUrl.getPort();
			String protocol=clientUrl.getProtocol();
			if(null==protocol || !(protocol.equals("http") || protocol.equals("https"))){
				protocol="http";
			}
			if(null==query){
				query="";
			}else{
				query="?"+query;
			}
			try {
				return this.commonGet(protocol,host, port, path, query);
			} catch (IOException e) {
				e.printStackTrace();
				return 0;
			}
		}else{
			return 0;
		}
	}
	
	public static void main(String[] argc){
		testNet();
	}
	private static void testNet() {
		String url="http://10.240.248.33:9526/UPDService/GetUPDOrganization.asmx/GetOrgListAll?appID=1";//?method=beetle_reRun&fileList=/home/beetle/inc/dn/sns/prize_log/20110403/account_login_log";
		System.out.print(doGet(url));
	}
	
	public static String doGet(String url) {
		int rsCode=0;
		//构造HttpClient的实例
		  HttpClient httpClient = new HttpClient();
		  //创建GET方法的实例
		  GetMethod getMethod = new GetMethod(url);
		  //使用系统提供的默认的恢复策略
		  getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				  new DefaultHttpMethodRetryHandler());
		  try {
			   //执行getMethod
			   int statusCode = httpClient.executeMethod(getMethod);
			   if (statusCode != HttpStatus.SC_OK) {
				   System.err.println("Method failed: " + getMethod.getStatusLine());
			   }else{
				   rsCode=statusCode;
//				   byte[] buf=new byte[CommonConstants.BUFFER_MAX];
//				   InputStream is=getMethod.getResponseBodyAsStream();
//				   is.read(buf);
//				   String rs=new String(buf).trim();
				   String rs=null;
				   ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
				   InputStream is=getMethod.getResponseBodyAsStream();
			        byte[] str_b = new byte[1024];
			        int i = -1;
			        while ((i=is.read(str_b)) > 0) {
			           outputstream.write(str_b,0,i);
			        }
			        rs = outputstream.toString();
				   return rs;
//				   System.out.println(rs);
			   }
		  } catch (HttpException e) {
			   //发生致命的异常，可能是协议不对或者返回的内容有问题
			   System.out.println("Please check your provided http address!");
			   e.printStackTrace();
		  } catch (IOException e) {
			   //发生网络异常
			   e.printStackTrace();
		  } finally {
			   //释放连接
			   getMethod.releaseConnection();
		  }
		return String.valueOf(rsCode);
	}
	public static String doPost(String url,List<NameValuePair> pairList){
		int rsCode=0;
		//构造HttpClient的实例
		  HttpClient httpClient = new HttpClient();
		  //创建POST方法的实例
		  PostMethod postMethod=new PostMethod(url);
//		  HttpMethodParams mParas=new HttpMethodParams();
//		  if(null!=paras&&0<paras.size()){
//			  Iterator<String> it=paras.keySet().iterator();
//			  while(it.hasNext()){
//				  String k=it.next();
//				  Object v=paras.get(k);
//				  mParas.setParameter(k, v);
//			  }
//		  }
//		  postMethod.setParams(mParas);
		  NameValuePair[] postData= new NameValuePair[pairList.size()];
		  pairList.toArray(postData);//new NameValuePair[paras.size()];
//		  if(null!=paras&&0<paras.size()){
//			  Iterator<String> it=paras.keySet().iterator();
//			  int i=0;
//			  while(it.hasNext()){
//				  String k=it.next();
//				  String v=paras.get(k);
//				  NameValuePair pair=new NameValuePair(k,v);
//				  postData[i++]=pair;
//			  }
//		  }
		  postMethod.setRequestBody(postData);
		  //使用系统提供的默认的恢复策略
		  postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				  new DefaultHttpMethodRetryHandler());
		  try {
			   //执行getMethod
			   int statusCode = httpClient.executeMethod(postMethod);
			   if (statusCode != HttpStatus.SC_OK) {
				   rsCode=statusCode;
				   System.err.println("Method failed: " + postMethod.getStatusLine());
			   }else{
//				   rsCode=statusCode;
//				   return postMethod.getResponseBodyAsString();
//				   byte[] buf=new byte[CommonConstants.BUFFER_MAX];
//				   InputStream is=postMethod.getResponseBodyAsStream();
//				   is.read(buf);
//				   return new String(buf).trim();
				   String rs=null;
				   ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
				   InputStream is=postMethod.getResponseBodyAsStream();
			        byte[] str_b = new byte[1024];
			        int i = -1;
			        while ((i=is.read(str_b)) > 0) {
			           outputstream.write(str_b,0,i);
			        }
			        rs = outputstream.toString();
				   return rs;
			   }
		  } catch (HttpException e) {
			   //发生致命的异常，可能是协议不对或者返回的内容有问题
			   System.out.println("Please check your provided http address!");
			   e.printStackTrace();
		  } catch (IOException e) {
			   //发生网络异常
			   e.printStackTrace();
		  } finally {
			   //释放连接
			  postMethod.releaseConnection();
		  }
		return String.valueOf(rsCode);
	}
}
